package edu.ustb.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtil {
	//定义一个常量
	public static final String CONFIG_FILE = "mybatis.xml";
	
	//创建工厂对象，静态代码块
	static SqlSessionFactory factory;
	static{
		
		initFactory(CONFIG_FILE);
		
	}
	private static void initFactory(String configFile) {
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		
		try {
			InputStream resourceAsStream = Resources.getResourceAsStream(configFile);
			
			factory = builder.build(resourceAsStream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	//本地线程
	static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
	//获取sqlSession
	public static SqlSession open(){
		SqlSession sqlSession = threadLocal.get();
		if(sqlSession==null){
			sqlSession = factory.openSession();
			threadLocal.set(sqlSession);
		}
		return sqlSession;
	}
	//关闭sqlSession
	public static void close(){
		SqlSession sqlSession = threadLocal.get();
		
		if(sqlSession!=null){
			sqlSession.close();
			threadLocal.set(null);
		}

	}
	//事务提交
	public static void commit(){
		SqlSession sqlSession = threadLocal.get();
		if(sqlSession!=null){
			sqlSession.commit();		
		}		
	}
	//事务回滚
	public static void rollback(){
		SqlSession sqlSession = threadLocal.get();
		if(sqlSession!=null){
			sqlSession.rollback();	
		}
	}
	public static <T> T getMapper(Class<T> tclass){
		
		return open().getMapper(tclass);
	}

}

